package com.soil.code.generation.domain.code.util;

import java.io.File;
import java.io.IOException;

/**
 * @author zeno
 */
public class CodeGenerationUtils{

  private static final String WINDOWS_FILE_SEPARATOR = "\\";
  private static final String LINUX_FILE_SEPARATOR = "/";

  private static final String JAVA_FILE_SUFFIX = ".java";

  /**
   * 创建代码的 file 对象
   * @param dir
   * @param pkg
   * @param className
   * @return
   */
  public static File createCodeFile(String dir, String pkg, String className) throws IOException{

    pkg = pkg.replace(".",File.separator);

    String lastChar = dir.substring(dir.length() - 1);
    if( WINDOWS_FILE_SEPARATOR.equals(lastChar) || LINUX_FILE_SEPARATOR.equals(lastChar) ){
      dir += pkg;
    }else {
      dir += File.separator + pkg;
    }

    File codeDir = new File(dir + File.separator);
    if( !codeDir.exists() ){
      if(!codeDir.mkdirs()){
        throw new IOException( "创建目录失败:" + codeDir.getAbsolutePath());
      }
    }

    String javaFilePath = codeDir.getAbsolutePath() + File.separator + className + JAVA_FILE_SUFFIX;
    return new File(javaFilePath);
  }


}
